package com.yloveg.common;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.yloveg.entity.VToken;
import com.yloveg.service.VTokenService;

 
public  class WeixinUtil {
	//老公司
	private final static String appid="wx58fb0633fc3c311c";
	private final static String secret="e316ad909524f73d1049825ec8044c27";
    private final static String area_url="http://tp1.ergreggvffv.top";

    //private final static String appid="wxf882faddca97fa23";
    //private final static String secret="1acbda88880304fef234c31394ed3fe0";
    //private final static String area_url="http://new2.tpglxtsix.top";

	  
	
	//授权地址获取
	@Cacheable(value="getAuthorizeUrl",key="#activityid")
	public static String getAuthorizeUrl(int activityid) {
		String activityUrl =area_url+"/vote-admin/free/playerList?activityid="+String.valueOf(activityid);
		String URLEncoded=UrlUtil.toURLEncoded(activityUrl);
		StringBuffer url = new StringBuffer();
		url.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
		url.append(appid);
		url.append("&redirect_uri=");
		url.append(URLEncoded);
		url.append("&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
		return url.toString();
	}
	
	//通过code换取access_token(此处的token和掉接口用的token不是一回事)
	public static JSONObject getAccess_token(String code) {
		JSONObject json =new JSONObject();
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = null;
		StringBuffer url = new StringBuffer();
		url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
		url.append(appid);
		url.append("&secret=");
		url.append(secret);
		url.append("&code=");
		url.append(code);
		url.append("&grant_type=authorization_code");
		responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null, String.class);
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
			String sessionData = responseEntity.getBody();
			JSONObject JS = JSONObject.parseObject(sessionData);
			return JS;
		}else{
			return null;
		}
	}

	//获取微信个人信息
	public static JSONObject getUserMsg(String access_token, String openid) {
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = null;
		// 微信的接口
		StringBuffer url = new StringBuffer();
		url.append("https://api.weixin.qq.com/sns/userinfo?access_token=");
		url.append(access_token);
		url.append("&openid=");
		url.append(openid);
		url.append("&lang=zh_CN");
		// 进行网络请求,访问url接口
		responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null, String.class);
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
			String sessionData = responseEntity.getBody();
			JSONObject JS = JSONObject.parseObject(sessionData);
			return JS;
		}else{
			return null;
		}
 
	}
	
	//获取用户信息一步到位。
    public static JSONObject getUserInfo(String code) {
    	JSONObject json =new JSONObject();
    	JSONObject tokenjson=getAccess_token(code);
    	if(tokenjson.containsKey("errcode")) {
			return tokenjson;
		}else {
			String access_token=tokenjson.getString("access_token");
    		String openid=tokenjson.getString("openid");
    		//拿用户基本信息
    		JSONObject userinfo=getUserMsg(access_token, openid);
    		return userinfo;
		}
    }
    
    //微信支付接口
    public static boolean payMoney(double amount) {
		
    	return true;
	}
    
	public static String getTicket(String access_token) {
		String ticket = null;
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";// 这个url链接和参数不能变																											//  
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求  
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			ticket = demoJson.getString("ticket");
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ticket;
	}
	
	public static String SHA1(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数  
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String getQianMing(String accessToken,String jsapi_ticket,String noncestr,String timestamp,String url){
		String str= "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
		System.out.println("str"+str);
		String signature =SHA1(str);
		System.out.println("参数："+str+"\n签名："+signature);
		return signature;
    }
    
    //微信分享签名信息获取
    public static Map getSharePram(String accessToken, String url) {
    	Map map = new HashMap();
    	String appId=appid;
    	String jsapi_ticket=WeixinUtil.getTicket(accessToken); 
    	String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16); 
    	String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
    	String signature=WeixinUtil.getQianMing(accessToken, jsapi_ticket, noncestr, timestamp, url); 
    	map.put("appId", appId);
    	map.put("timestamp", timestamp);
    	map.put("nonceStr", noncestr);
    	map.put("signature", signature);
    	return map;
    }
}
